package com.qianfeng.iot.backip.service.impl;

//
//                            _ooOoo_  
//                           o8888888o  
//                           88" . "88  
//                           (| -_- |)  
//                            O\ = /O  
//                        ____/`---'\____  
//                      .   ' \\| |// `.  
//                       / \\||| : |||// \  
//                     / _||||| -:- |||||- \  
//                       | | \\\ - /// | |  
//                     | \_| ''\---/'' | |  
//                      \ .-\__ `-` ___/-. /  
//                   ___`. .' /--.--\ `. . __  
//                ."" '< `.___\_<|>_/___.' >'"".  
//               | | : `- \`.;`\ _ /`;.`/ - ` : | |  
//                 \ \ `-. \_ __\ /__ _/ .-` / /  
//         ======`-.____`-.___\_____/___.-`____.-'======  
//                            `=---='  
//  
//         .............................................  
//                  佛祖镇楼                  BUG辟易  
//          佛曰:  
//                  写字楼里写字间，写字间里程序员；  
//                  程序人员写程序，又拿程序换酒钱。  
//                  酒醒只在网上坐，酒醉还来网下眠；  
//                  酒醉酒醒日复日，网上网下年复年。  
//                  但愿老死电脑间，不愿鞠躬老板前；  
//                  奔驰宝马贵者趣，公交自行程序员。  
//                  别人笑我忒疯癫，我笑自己命太贱；  
//  


import cn.hutool.core.lang.UUID;
import com.dc3.common.bean.R;
import com.dc3.common.model.BlackIp;
import com.qianfeng.iot.backip.event.BlackChangeEvent;
import com.qianfeng.iot.backip.service.BlackIpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.data.relational.core.query.Query;
import org.springframework.data.relational.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * Created by Jackiechan on 2022/8/3 21:03
 *
 * @author Jackiechan
 * @version 1.0
 * @since 1.0
 */
@Service
@Transactional
public class BlackIpServiceImpl implements BlackIpService {

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    private R2dbcEntityTemplate r2dbcEntityTemplate;

    @Autowired
    public void setR2dbcEntityTemplate(R2dbcEntityTemplate r2dbcEntityTemplate) {
        this.r2dbcEntityTemplate = r2dbcEntityTemplate;
    }

    @Override
    public Mono<R<Object>> addBlackIp(Mono<BlackIp> blackIpMono) {
        //首先要校验数据,
        // 因为我们并不是真正的删除数据,所以在添加的时候要判断数据在不在, 如果在,并且是未删除状态就返回已经存在,如果是删除状态,则改回正常的
        return blackIpMono
                .flatMap(blackIp -> {
                    blackIp.setId(UUID.randomUUID().toString(true));
                    return r2dbcEntityTemplate.insert(BlackIp.class).into("dc3_black_ip").using(blackIp);
                })
                .doOnError(throwable -> throwable.printStackTrace())
                .map(blackIp -> {
                            //添加成功后先同步缓存
                            syncBlackCache();
                            return R.ok("添加成功");
                        }
                )
                .onErrorReturn(R.fail("添加失败"));
    }

    @Override
    public Flux<BlackIp> findAllEnableIp() {
        return r2dbcEntityTemplate
                .select(BlackIp.class)
                .from("dc3_black_ip")
                .matching(Query.query(Criteria.where("enable").is(1))).all();
    }

    @Override
    public void syncBlackCache() {
        context.publishEvent(new BlackChangeEvent());
    }

    @Override
    public Mono<Integer> deleteIp(List<String> ips) {
//        Mono<Integer> result = r2dbcEntityTemplate.delete(BlackIp.class).from("dc3_black_ip")
//                .matching(Query.query(Criteria.where("ip").in(ips))).all();
        Mono<Integer> result = r2dbcEntityTemplate.update(BlackIp.class)
                .inTable("dc3_black_ip")
                .matching(Query.query(Criteria.where("ip").in(ips)))
                .apply(Update.update("enable", 0).set("deleted", 1))
                .doOnSuccess(integer -> syncBlackCache());
        return result;
    }
}
